import json
import logging
import os
from pathlib import Path
from typing import Dict, Any, List  # 定义智能体模型

# 获取项目根目录
BASE_DIR = Path(__file__).resolve().parent.parent
# 上传文件夹路径
UPLOAD_FOLDER_PATH = os.path.join(BASE_DIR, "uploads")
# 获取工具配置文件路径
TOOLS_DIR = os.path.join(UPLOAD_FOLDER_PATH, 'tools')
TOOLS_CONFIG_PATH = os.path.join(UPLOAD_FOLDER_PATH, 'AgentToolsConfig.json')
COMMON_TOOLS_PATH = os.path.join(UPLOAD_FOLDER_PATH, 'CommonTools.json')
# MCP工具配置文件路径
MCP_TOOLS_PATH = os.path.join(UPLOAD_FOLDER_PATH, 'mcpTools.json')
# MCP INSTALL TOOL配置文件路径
MCP_INSTALL_TOOLS_PATH = os.path.join(UPLOAD_FOLDER_PATH, 'mcpInstallTools.json')

# 文档存储目录
DOC_FOLDER_PATH = os.path.join(UPLOAD_FOLDER_PATH, "doc")

# 确保目录存在
os.makedirs(UPLOAD_FOLDER_PATH, exist_ok=True)
os.makedirs(DOC_FOLDER_PATH, exist_ok=True)


class FileHandle(Dict[str, Any]):
    pass


# 读取通用工具配置文件
def read_common_tools() -> Dict[str, Any]:
    try:
        with open(COMMON_TOOLS_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return {"quickTools": [], "MCPTools": [], "workflowComponents": []}
    except json.JSONDecodeError:
        return {"quickTools": [], "MCPTools": [], "workflowComponents": []}


# 写入常用工具配置文件
def write_common_tools(data: Dict[str, Any]) -> None:
    with open(COMMON_TOOLS_PATH, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


# 读取工具配置文件
def read_tools_config() -> List[Dict[str, Any]]:
    try:
        with open(TOOLS_CONFIG_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        # 如果文件不存在，创建一个空列表
        with open(TOOLS_CONFIG_PATH, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False, indent=2)
        return []
    except json.JSONDecodeError:
        # 如果JSON解析失败，返回空列表
        return []


# 写入工具配置文件
def write_tools_config(data: List[Dict[str, Any]]) -> None:
    with open(TOOLS_CONFIG_PATH, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def load_mcp_tools_config(tool_ids: list) -> list:
    """
    从配置文件加载MCP工具配置，基于嵌套的JSON结构
    
    Args:
        tool_ids: 要加载的工具ID列表
        
    Returns:
        匹配ID的工具配置列表
    """
    logger = logging.getLogger('MCP-Tool')

    try:
        config_path = MCP_INSTALL_TOOLS_PATH

        if not os.path.exists(config_path):
            logger.warning(f"工具配置文件不存在: {config_path}")
            return []

        with open(config_path, 'r', encoding='utf-8') as f:
            config_data = json.load(f)

        selected_tools = []
        # 处理嵌套的JSON结构
        for tool in config_data:
            if isinstance(tool, dict) and "id" in tool and tool["id"] in tool_ids:
                selected_tools.append(tool)
        return selected_tools

    except Exception as e:
        logger.error(f"加载工具配置失败: {str(e)}", exc_info=True)
        return []
